#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <regex>

#include "../include/deckparser.h"
#include "../include/cardprovider.h"
#include "../include/card.h"

using namespace std;

namespace mtga {

	DeckParser::DeckParser(CardProvider* cardProvider) {
		std::cout << "Creating DeckParser (" << this << ")" << std::endl;
		this->cardProvider = cardProvider;
	}

	DeckParser::~DeckParser() {
		std::cout << "Releasing DeckParser (" << this << ")" << std::endl;
	}

	void DeckParser::loadFromFile(Deck* deck, string format, string filename) {
		std::cout << "Loading deck from file " << filename << std::endl;
		std::ifstream inputStream;
		inputStream.open(filename.c_str());
		std::string line;
		std::vector<std::string> elements;
		int count = 0;
		while (std::getline(inputStream, line)) {
			if (line.size() == 0) {
				continue;
			}
			std::cout << "Processing element '" << line << "'" << std::endl;
			// TODO use regular expression:
			// {SB:} {digit} {name}
			bool isSideboard = false;
			if (line.substr(0, 3).compare("SB:") == 0) {
				isSideboard = true;
				std::cout << "Sideboard option" << std::endl;
				line = line.substr(4, line.size() - 1);
			}
			int index = line.find(" ");
			std::string countStr = line.substr(0, index);
			std::string name = line.substr(index + 1, line.size() - 1);
			std::cout << "  [" << countStr << "]: [" << name << "]" << std::endl;
			int count;
			std::istringstream ss(countStr);
			ss >> count;
			Card* card = this->cardProvider->findByName(name);
			if (!isSideboard) {
				deck->addCard(card, count);
			} else {
			}
		}
		std::cout << "Readed " << count << " cards" << std::endl;
	}

}
